package com.capgemini.cn.authority.data.repository;

import com.capgemini.cn.authority.data.entity.Asserts;
import com.capgemini.cn.authority.data.entity.AssertsGroup;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import javax.persistence.LockModeType;
import java.util.List;

/**
 * Created at 2017/8/24
 *
 * @author Andriy
 */
@Repository
public interface AssertsRepository extends JpaRepository<Asserts, Long> {

    /**
     * 根据资源值查询资源信息
     *
     * @param assertValue 资源值
     */
    Asserts findByAssertValue(@Param(value = "assertValue") String assertValue);

    /**
     * 根据资源值查询资源信息 - <span style='color:yellow'>使用悲观写锁控制数据脏读</span>
     *
     * @param assertValue 资源值
     */
    @Lock(value = LockModeType.PESSIMISTIC_WRITE)
    Asserts findByAssertValueEquals(@Param(value = "assertValue") String assertValue);

    /**
     * 查询指定资源组且不包含对应资源内容的资源列表信息 - <span style='color:yellow'>使用悲观写锁控制数据脏读</span>
     *
     * @param assertsGroup 指定资源组对象
     * @param assertValues 排除在外的资源值列表信息
     */
    @Lock(value = LockModeType.PESSIMISTIC_WRITE)
    List<Asserts> findAllByAssertsGroupAndAssertValueNotIn(AssertsGroup assertsGroup, String[] assertValues);

    /**
     * 根据权限查询其所有的资源数据信息
     *
     * @param authorityId 权限主键ID值
     */
    @Query(nativeQuery = true, value = "SELECT a.* FROM cg_asserts a LEFT JOIN cg_asserts_group_authorities aga ON aga.authority_id=:authorityId WHERE a.assert_group_id=aga.assert_group_id")
    List<Asserts> findAuthorityOwnedAsset(@Param(value = "authorityId") long authorityId);
}
